<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="70px"
    >
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="维修时间" prop="timeRange">
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          size="small"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          align="right"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equipment:repairTask:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:repairTask:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment:repairTask:remove']"
          >删除</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :loading="btnLoading"
          v-hasPermi="['equipment:repairTask:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-s-opportunity"
          size="mini"
          :disabled="multiple"
          @click="handleComplete"
          v-hasPermi="['equipment:repairTask:finish']"
          >完成任务</el-button
        >
      </el-col>
      <!-- <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <el-table
      :cell-style="{ padding: this.tablePadding }"
      v-loading="loading"
      :data="repairTaskList"
      border
      height="350"
      @selection-change="handleSelectionChange"
      highlight-current-row
      @row-click="getInfoItem"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="维修任务名称"
        min-width="100px"
        align="center"
        prop="repairTaskName"
      />
      <el-table-column label="设备名称" align="center" prop="equipmentName" />
      <el-table-column label="执行者" align="center" prop="repairManName" />
      <el-table-column
        label="维修时间"
        align="center"
        prop="startTime"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.repairTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="是否外协维修"
        align="center"
        prop="isAssistRepair"
        :formatter="isAssistRepairFormat"
        width="100px"
      />
      <el-table-column
        label="保养单位"
        :show-overflow-tooltip="true"
        align="center"
        prop="supplierName"
        width="180px"
      />
      <el-table-column
        label="联系方式"
        :show-overflow-tooltip="true"
        align="center"
        prop="contactsPhone"
        width="110px"
      />
      <el-table-column
        label="维修任务状态"
        align="center"
        prop="status"
        width="110"
        :formatter="statusFormat"
      />
      <el-table-column
        label="维修总金额"
        align="center"
        prop="money"
        width="100px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:repairTask:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:repairTask:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-row style="padding: 20px 0">
      <el-tabs>
        <el-tab-pane label="维修任务明细">
          <tab-details
            ref="paramRef"
            @delFunc="delFunc"
            :repairTaskList="detailsData.equipmentRepairTaskDetails"
          />
        </el-tab-pane>
        <el-tab-pane label="维修任务附件">
          <!-- <tab-file ref="priceRef"/> -->
          <div style="width: 400px; min-height: 200px" v-show="repairTaskId">
            <file-upload
              :isShowTip="true"
              :limit="10"
              :fileSize="0"
              :noResfileSize="false"
              :value="fileValue"
              @setFile="setFile"
              @delFile="delFile"
            />
          </div>
          <div v-show="!repairTaskId" class="no-data-txt">暂无数据</div>
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <!-- 添加或修改设备维修对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form
        ref="form"
        :inline="true"
        layout="inline"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="是否外协">
          <div style="width: 503px">
            <el-radio-group v-model="form.isAssistRepair">
              <el-radio
                v-for="dict in isAssistRepairOptions"
                :key="dict.dictValue"
                :label="parseInt(dict.dictValue)"
                >{{ dict.dictLabel }}</el-radio
              >
            </el-radio-group>
          </div>
        </el-form-item>

        <el-form-item label="维修任务名称" prop="repairTaskName">
          <el-input v-model="form.repairTaskName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="设备" prop="equipmentId">
          <div class="input-width">
            <el-select
              v-model="form.equipmentId"
              placeholder="请选择设备"
              clearable
            >
              <el-option
                v-for="item in equipmentOptions"
                :key="item.equipmentId"
                :label="item.equipmentName"
                :value="item.equipmentId"
                :disabled="item.status == 0"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <div class="input-width">
            <treeselect
              v-model="form.deptId"
              :options="deptOptions"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="选择部门"
            />
          </div>
        </el-form-item>
        <!-- 保养单位 -->
        <el-form-item label="保养单位" :prop="form.isAssistRepair==0?'':'supplierId'">
          <div class="input-width">
            <el-select
              v-model="form.supplierId"
              @change="supplierChange"
              :disabled="form.isAssistRepair==0"
              :placeholder="form.isAssistRepair==0?'':'请选择保养单位'"
            >
              <el-option
                v-for="item in supplierOptions"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactsPhone">
          <el-input disabled v-model="form.contactsPhone" />
        </el-form-item>
        <el-form-item label="维修时间" prop="repairTime">
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="form.repairTime"
            type="date"
            placeholder="选择维修日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维修金额">
          <el-input v-model="form.money" placeholder="请输入维修金额" />
        </el-form-item>
        <el-form-item label="执行人" prop="repairMan">
          <div class="input-width">
            <el-select v-model="form.repairMan" placeholder="请选择执行人">
              <el-option
                v-for="item in repairManOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <dedcribe ref="dedcribeRef" :selectItems="dedcribeList" />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="btnLoading" v-funThrottle="[submitForm]">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRepairTask,
  getRepairTask,
  delRepairTask,
  addRepairTask,
  updateRepairTask,
  getRepairManOptions,
  getRepairTaskFile,
  setRepairTaskFile,
  delRepairTaskFile,
  repairTaskFinish,
} from "@/api/equipment/repairTask";

import { listDept } from "@/api/system/dept";
import { listInfo, getResponseManOptions } from "@/api/equipment/info";
import { getSupplierOption } from "@/api/base/supplier";
import TabDetails from "./components/TabDetails";
import FileUpload from "@/components/FileUpload";
import Dedcribe from "./components/Describe.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "RepairTask",
  components: { TabDetails, FileUpload, Dedcribe, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备维修表格数据
      repairTaskList: [],
      dedcribeList: [],
      fileValue: [], //任务附件
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否外协维修字典
      isAssistRepairOptions: [],
      // 任务状态 0初始化 1维修成功 2维修失败字典
      statusOptions: [],
      detailsData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentId: null,
        equipmentName: null,
        deptIds: null,
        startTime: null,
        status: null,
      },
      defaultProps: {
        children: "children",
        label: "deptName",
      },
      // 组织选项
      equipmentOptions: [],
      queryDeptIds: null,
      repairManOptions: [],
      supplierOptions: [],
      deptOptions: [],
      repairTaskId: null,
      // 表单参数
      form: {},
      selectNames: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setHours("0");
              start.setMinutes("0");
              start.setSeconds("0");
              // start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      timeRange: [],
      btnLoading:false,
      // 表单校验
      rules: {
        deptId: [{ required: true, message: "部门不能为空", trigger: "blur" }],
        repairTime: [
          { required: true, message: "维修时间不能为空", trigger: "blur" },
        ],
        repairTaskName: [
          { required: true, message: "维修任务名称不能为空", trigger: "blur" },
        ],
        equipmentId: [
          { required: true, message: "设备ID不能为空", trigger: "blur" },
        ],

        repairMan: [
          { required: true, message: "执行者不能为空", trigger: "blur" },
        ],
        isAssistRepair: [
          { required: true, message: "是否外协维修不能为空", trigger: "blur" },
        ],
        supplierId: [
          { required: true, message: "保养单位不能为空", trigger: "blur" },
        ],
        status: [
          {
            required: true,
            message: "任务状态不能为空",
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "任务描述不能为空", trigger: "blur" },
        ],
        createBy: [
          { required: true, message: "建立人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "建立时间不能为空", trigger: "blur" },
        ],
        updateBy: [
          { required: true, message: "修改人不能为空", trigger: "blur" },
        ],
        updateTime: [
          { required: true, message: "修改时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getSulipperOptions();
    this.getRepairManOptions();
    this.getEquipmentOptions();
    this.getDeptOptions();
    this.getDicts("repair_task_status").then((response) => {
      this.isAssistRepairOptions = response.data;
    });
    this.getDicts("equipment_task_status").then((response) => {
      this.statusOptions = response.data;
    });
  },
  watch:{
     'form.isAssistRepair': function (val, oldVal) {
      if(val==0){
        this.form.supplierId=''
        this.form.contactsPhone=''
      }
    }
  },
  methods: {
    // 选择完供应商，显示联系方式
    supplierChange(id) {
      if(!id) return;
      var obj = this.supplierOptions.find(function (x) {
        return x.supplierId === id;
      });
      this.form.contactsPhone = obj.contactsPhone;
    },
    // 完成任务
    handleComplete() {
      repairTaskFinish(this.ids).then((res) => {
        this.msgSuccess("操作成功");
        this.getList();
      });
    },
    // 删除附件
    delFile(file) {
      delRepairTaskFile(file.repairAttachId).then((res) => {
        this.getFile();
      });
    },
    // 上传附件
    setFile(url, name) {
      let obj = {
        attachUrl: url,
        attachName: name,
        repairTaskId: this.repairTaskId,
      };
      setRepairTaskFile(obj).then((response) => {
        // 获取附件
        this.getFile();
      });
    },
    // 获取附件
    getFile() {
      getRepairTaskFile(this.repairTaskId).then((response) => {
        this.fileValue = response.data.map((item) => {
          return {
            repairAttachId: item.repairAttachId,
            name: item.attachUrl,
            url: item.attachUrl,
          };
        });
      });
    },
    delFunc() {
      getRepairTask(this.repairTaskId).then((response) => {
        this.detailsData = response.data;
      });
    },
    // 获取详情
    getInfoItem(row) {
      this.repairTaskId = row.repairTaskId;
      getRepairTask(this.repairTaskId).then((response) => {
        this.detailsData = response.data;
      });
      // 获取附件
      this.getFile();
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
        isDisabled: node.status == 1 ? true : false,
      };
    },
    /** 查询设备维修列表 */
    getList() {
      this.loading = true;
      listRepairTask(this.queryParams).then((response) => {
        this.repairTaskList = response.rows;
        // if (this.repairTaskList.length > 0) {
        //    this.getInfoItem(this.repairTaskList[0]);
        // }else{
        this.fileValue = [];
        this.detailsData = {};
        // }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 是否外协维修字典翻译
    isAssistRepairFormat(row, column) {
      return this.selectDictLabel(
        this.isAssistRepairOptions,
        row.isAssistRepair
      );
    },
    getEquipmentOptions() {
      listInfo().then((response) => {
        this.equipmentOptions = response.rows;
        this.loading = false;
      });
    },
    getDeptOptions() {
      listDept().then((response) => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    getSulipperOptions() {
      getSupplierOption().then((response) => {
        this.supplierOptions = response.data;
        this.loading = false;
      });
    },
    getRepairManOptions() {
      // getRepairManOptions().then((response) => {
      //   this.repairManOptions = response.rows;
      //   this.loading = false;
      // });
      getResponseManOptions().then((response) => {
        this.repairManOptions = response.rows;
        this.loading = false;
      });
    },
    // 任务状态 0初始化 1维修成功 2维修失败字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        repairTaskId: null,
        repairTaskName: null,
        billCode: null,
        equipmentId: null,
        deptId: null,
        repairMan: null,
        startTime: null,
        endTime: null,
        isAssistRepair: 0,
        supplierId: null,
        status: 0,
        description: null,
        money: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.timeRange.length > 0) {
        this.queryParams.startTime = this.timeRange[0];
        this.queryParams.endTime = this.timeRange[1];
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.timeRange = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.repairTaskId);
      this.selectNames = selection.map((item) => item.repairTaskName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备维修";
      this.dedcribeList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const repairTaskId = row.repairTaskId || this.ids;
      getRepairTask(repairTaskId).then((response) => {
        this.form = response.data;
        // 处理问题描述表格
        this.dedcribeList = this.form.equipmentRepairTaskDetails;
        this.supplierChange(this.form.supplierId);
        this.open = true;
        this.title = "修改设备维修";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
           this.btnLoading=true
          if (this.form.repairTaskId != null) {
            this.form.equipmentRepairTaskDetails =
              this.$refs.dedcribeRef.filterSelect();
            updateRepairTask(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            this.btnLoading=false
            }).catch(()=>{
              this.btnLoading=false
            });
          } else {
            this.form.equipmentRepairTaskDetails =
              this.$refs.dedcribeRef.filterSelect();
            addRepairTask(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            this.btnLoading=false
            }).catch(()=>{
              this.btnLoading=false
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const repairTaskIds = row.repairTaskId || this.ids;
      const name = row.repairTaskName || this.selectNames;
      this.$confirm('是否确认删除名称为"' + name + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",closeOnClickModal:false,
        type: "warning",
      })
        .then(function () {
          return delRepairTask(repairTaskIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.btnLoading=true
      this.download(
        "equipment/repairTask/export",
        {
          ...this.queryParams,
        },
        `equipment_repairTask.xlsx`,
        '',
        ()=>{
          this.btnLoading=false
        }
      );
    },
  },
};
</script>
<style  scoped>
</style>